import global from '@/config/index'
import { useUserStore } from '@/store'

interface R {
    code: number,
    errormsg: string,
    data: any
}


const install = () =>{
    let _u : any = uni.$u
    const userStore = useUserStore()
    _u.http.setConfig({
        baseUrl: global.BASE_URL_API,
        loadingText: '疯狂加载中...',
        loadingTime: 800
    })

    // 请求拦截，配置Token等参数
    _u.http.interceptor.request = (config: any) => {
        // 校验token并补请求头
        const token = userStore.token
        if (token) {
            config.header['MERCHANT-token'] = token
        }
        // 判断是否为json请求
        if (config.header.useJsonParam) {
            if (config.method && config.method.toUpperCase() === 'POST') {
                config.header['Content-Type'] = 'application/json';
            }
            delete config.header.useJsonParam
        } else if (config.header.useFormParam) {
            config.header['Content-type'] = config.header['Content-type'] ? config.header['Content-type'] :
                'multipart/form-data';
            delete config.header.useFormParam
        } else {
            if (config.method && config.method.toUpperCase() === 'POST') {
                config.header['Content-Type'] = config.header['Content-Type'] ? config.header['Content-Type'] :
                    'application/x-www-form-urlencoded';
            }
        }
        if (config.header.onUploadProgress) {
            config.onUploadProgress = config.header.onUploadProgress
            delete config.header.onUploadProgress
        }
        // 是否有遮罩层

        if (config.header.useMask) {
            config.showLoading = true
            config.loadingMask = true
            delete config.header.useMask
        }
        return config
    }
    // 重写get请求
    _u.get = (url:string, data:any, header:object) => {
        return new Promise((resolve, reject) => {
            _u.http.get(url, data, header).then((res: R) => {
                if (thenDeal(res, url)) {
                    resolve(res.data)
                } else {
                    reject(res.errormsg)
                }
            }).catch((error: any) => {
                catchError(error)
                reject(error)
            })
        })
    }
    // 重写post请求
    _u.post = (url:string, data:any, header:any) => {
        return new Promise((resolve, reject) => {
            _u.http.post(url, data, header).then((res: R) => {
                if (thenDeal(res, url)) {
                    resolve(res.data)
                } else {
                    reject(res.errormsg)
                }
            }).catch((error: any) => {
                catchError(error)
                reject(error)
            })
        })
    }

    function thenDeal(res: R, url: string) {
        if (res && res.code === 7) {
            // 进行一次自动登录
            let ret = res.errormsg.split(',')
            let message = ''
            if (ret.length > 1) {
                if (ret[0] === '强制退出') {
                    message = `当前帐号已在[${ret[1]}]上登录，`
                }
            } else if (ret.length === 1) {
                message = '当前帐号登录已过期，'
            }
            console.log('触发一次重新登录弹窗', url);
            _u.$showModal({
                title: '温馨提示',
                content: `${message}请重新登录！`,
                showCancel: false,
                noBack: true,
                success: (res: any) => {
                    userStore.LogOut().then(() => {
                        _u.$MRouter.login.to()
                    })
                }
            })
            return false
        } else if (res && res.code === 0) {
            _u.toast(res.errormsg);
            return false
        } else if (res && res.code === 1) {
            return true
        } else {
            return false
        }
    }

    function catchError(error: any) : boolean{
        let msg = ''
        if (error) {
            switch (error.statusCode) {
                case 400:
                    msg = '请求无效'
                    break
                case 401:
                    msg = '没有权限访问'
                    break
                case 403:
                    msg = '禁止访问'
                    break
                case 404:
                    msg = '404'
                    break
                case 500:
                    msg = '请求异常'
                    break
                case 503:
                    msg = '服务连接异常'
                    break
                case 200:
                    msg = 'OK'
                    break
                default:
                    msg = '请检查网络连接之后重试'
                    break
            }
        }
        _u.toast(msg);
        return false
    }
}

export  default install
